import {createRouter, createWebHistory} from 'vue-router'

const arr: string[] = [
    '/login',
    '/register'
]

const router = createRouter({
    history: createWebHistory(import.meta.env.BASE_URL),
    routes: [
        {
            path: '/',
            name: 'home',
            component: () => import('../views/HomeView.vue')
        },
        {
            path: '/about',
            name: 'about',
            component: () => import('../views/AboutView.vue')
        },
        {
            path: '/login',
            name: 'login',
            component: () => import('../views/users/LoginView.vue')
        },
        {
            path: '/register',
            name: 'register',
            component: () => import('../views/users/RegisterView.vue')
        }
    ]
})

router.beforeEach((to, from, next) => {
    const token: string = localStorage.getItem('token') as string
    // 路由白名单
    if (arr.includes(to.path)) {
        next()
        return
    }
    if (token == null) {
        next('/login')
    } else {
        next()
    }
})

export default router
